<?php

ini_set('session.use_trans_sid', false);
ini_set('session.use_only_cookies', true);

define('INIT_TIMESTAMP', microtime());


include '../!inc.php';


if (true !== session_start()) {
    throw new StudyBuddy\Exception('session start error');
}

require($StudyBuddyClasses . 'Base.php');
require($StudyBuddyClasses . 'WebPage.php');
require($StudyBuddyClasses . 'Forms' . DIRECTORY_SEPARATOR . 'Form.php');
require($StudyBuddyClasses . 'Cookie.php');
require($StudyBuddyClasses . 'LoginForm.php');


try {

    if (!empty($_SESSION['oViewer'])) {
        d('SESSION: ' . print_r($_SESSION, 1) . ' oViewer in session: ' . print_r($_SESSION['oViewer']->getArrayCopy(), 1));
    } else {
        d('No Viewer is $_SESSION');
    }

    $oRequest = $oRegistry->Request;
    $a = $oRequest['a'];

    $controller = ucfirst($a);
    include($StudyBuddyClasses . 'Controllers' . DIRECTORY_SEPARATOR . $controller . '.php');
    $class = '\StudyBuddy\\Controllers\\' . $controller;

    header('Content-Type: text/html; charset=utf-8');
    echo new $class($oRegistry);
    fastcgi_finish_request();

    //$_SESSION['oViewer']->save();
    //$oRegistry->Viewer = null;
    //session_write_close();
} catch (\Exception $e) {
    header("HTTP/1.0 500 Exception");
    try {
        $sHtml = \StudyBuddy\Responder::makeErrorPage('<strong>Error:</strong> ' . StudyBuddy\Exception::formatException($e));
        $extra = (isset($_SERVER)) ? ' $_SERVER: ' . print_r($_SERVER, 1) : ' no server';
        $extra .= 'file: ' . $e->getFile() . ' line: ' . $e->getLine() . ' trace: ' . $e->getTraceAsString();
        if (defined('STUDYBUDDY_DEVELOPER_EMAIL') && strlen(trim(constant('STUDYBUDDY_DEVELOPER_EMAIL'))) > 1) {
            @mail(STUDYBUDDY_DEVELOPER_EMAIL, '500 Error in index.php', $sHtml . $extra);
        }
        echo $sHtml;
        fastcgi_finish_request();
    } catch (\Exception $e2) {
        $sHtml = \StudyBuddy\Responder::makeErrorPage('<strong>Exception:</strong> ' . strip_tags($e2->getMessage()) . "\nIn file:" . $e2->getFile() . "\nLine: " . $e2->getLine());
        $extra = (isset($_SERVER)) ? ' $_SERVER: ' . print_r($_SERVER, 1) : ' no extra';
        if (defined('STUDYBUDDY_DEVELOPER_EMAIL') && strlen(trim(constant('STUDYBUDDY_DEVELOPER_EMAIL'))) > 1) {
            @mail(STUDYBUDDY_DEVELOPER_EMAIL, 'Error in index.php on line ' . __LINE__, $sHtml . $extra);
        }
        echo $sHtml;
        fastcgi_finish_request();
    }
}
